﻿using System;
using System.Collections.Generic;
using System.Linq;
using VoiceAd.Models;

namespace VoiceAd.DAL
{
    public class SendMailGroupRepository : ISendMailGroupRepository, IDisposable
    {
        private dbVoiceAdDataContext context = new dbVoiceAdDataContext();

        public SendMailGroupRepository(dbVoiceAdDataContext db)
        {
            this.context = db;
        }

        public IEnumerable<tblSendMailGroup> GetList()
        {
            return context.tblSendMailGroups.ToList();
        }

        public IEnumerable<tblGroupMail> GetListGroup(int CampaignId)
        {
            return context.tblSendMailGroup_GetlistGroup(CampaignId);
        }

        public tblSendMailGroup GetById(int id)
        {
            return context.tblSendMailGroups.Where(x => x.Id == id).FirstOrDefault();
        }

        public IEnumerable<tblSendMailGroup> GetByCampaignID(int lCampaignId)
        {
            return context.tblSendMailGroups.Where(x => x.CampaignId == lCampaignId).ToList();
        }

        public IEnumerable<tblSendMailGroup> GetByCampaignIDGroupNum(int lCampaignId, int lGroupNum)
        {
            return context.tblSendMailGroups.Where(x => x.CampaignId == lCampaignId && x.GroupNum == lGroupNum).ToList();
        }

        public void Ins(tblSendMailGroup tbl)
        {
            context.tblSendMailGroups.InsertOnSubmit(tbl);
            context.SubmitChanges();
        }

        public void Upd(tblSendMailGroup tbl)
        {
            tblSendMailGroup obj = context.tblSendMailGroups.Where(x => x.Id == tbl.Id).First();
            obj.CampaignId = tbl.CampaignId;
            obj.GroupNum = tbl.GroupNum;
            obj.Email = tbl.Email;
            obj.Status = tbl.Status;
            obj.StationId = tbl.StationId;
            context.SubmitChanges();
        }

        public void Del(int id)
        {
            tblSendMailGroup obj = context.tblSendMailGroups.Single(x => x.Id == id);
            context.tblSendMailGroups.DeleteOnSubmit(obj);
            context.SubmitChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}